package cn.meomis.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import cn.meomis.common.entity.Pagination;
import cn.meomis.common.util.DataTableParam;
import cn.meomis.model.Che;
import cn.meomis.model.SysLog;
import cn.meomis.model.Value;
import cn.meomis.service.CheService;
import cn.meomis.service.SysLogService;
import cn.meomis.service.ValueDetailService;
import cn.meomis.service.ValueService;

//@Scope("prototype") 
@Controller
//@Namespace("/")
@ParentPackage("json-default")
//@Result(name="success", type="json")
public class ValueAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	private SimpleDateFormat dateformat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private Value value;
	
	// @Resource
	@Autowired
	private ValueService valueService;
	@Autowired
	private CheService cheService;
	
	@Autowired
	private ValueDetailService valueDetailService;
	
	@Autowired
	private SysLogService sysLogService;		//日志

	
	@Action(value = "/valueAction", results = { @Result(name = SUCCESS, location = "/manager/modules/value/value.jsp")})
	@Override
	public String execute() {
/*		String type = httpServletRequest.getParameter("type");
		List<Demo> demoList = valueService.findAll();
		httpServletRequest.setAttribute("DEMO_LIST", demoList);
		if ("manager".equals(type)) {
			return "manager";
		}*/
		List<Che> cheList = cheService.findAll();
		httpServletRequest.setAttribute("CHE_LIST", cheList);
		return SUCCESS;
	}
	
	@Action(value = "/findValueAction", results = { @Result(name = SUCCESS, location = "/manager/modules/value/edit.jsp") })
	public String find(){
		Value v = valueService.findById(Integer.parseInt(httpServletRequest.getParameter("id")));
		httpServletRequest.setAttribute("VALUE", v);
		List<Che> cheList = cheService.findAll();
		httpServletRequest.setAttribute("CHE_LIST", cheList);
		return SUCCESS;
	}

	@Action(value = "/valueEditAction", results = { @Result(name = SUCCESS, location = "/valueAction.action", type = "redirect") })
	public String cheEdit() throws UnsupportedEncodingException {
		Value valueInstance = valueService.findById(value.getId());
		
		try {
			SysLog sl = new SysLog();
			sl.setContent("编辑车属性,修改前名称[" + valueInstance.getTypename()
					+ "],修改后名字[" + value.getTypename() + "],修改前阀门值["
					+ valueInstance.getValue() + "],修改后阀门值[" + value.getValue()
					+ "]");
			sl.setCreateDate(new Date());
			sysLogService.save(sl);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		valueInstance.setCreatedate(new Date());
		valueInstance.setTypename(new String(value.getTypename().getBytes("ISO-8859-1"),"utf-8"));
//		valueInstance.setTypename(value.getTypename());
		valueInstance.setValue(value.getValue());
		valueInstance.setCheId(value.getCheId());
//		valueInstance.setDes(new String(che.getDes().getBytes("ISO-8859-1"),"utf-8"));
//		user.setUserid(new String(httpServletRequest.getParameter("userid").getBytes("ISO-8859-1"),"utf-8"));
		valueService.save(valueInstance);
		
		return SUCCESS;
	}
	
	@Action(value="/valueAddAction",results=@Result(name="success", type="json"))
	public void addNotice(){
		String result = "success";
		try {
			value.setCreatedate(new Date());
			valueService.save(value);
			
			try {
				SysLog sl = new SysLog();
				sl.setContent("创建车属性,名字["+value.getTypename()+"],车类型,名称["+cheService.findById(value.getCheId()).getName()+"]");
				sl.setCreateDate(new Date());
				sysLogService.save(sl);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} catch (Exception e1) {
			e1.printStackTrace();
			result = "error";
		}
		
		httpServletResponse.setContentType("application/Json");
		JSONObject jsonResponse = new JSONObject();	
		try {
			jsonResponse.put("isSorF", result);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		try {
			httpServletResponse.getWriter().print(jsonResponse.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Action(value = "/valueDeleteAction", results = { @Result(name = SUCCESS, location = "/demoAction.action?type=manager", type = "redirect") })
	public String delete() {
		valueService.removeById(Integer.parseInt(httpServletRequest
				.getParameter("id")));
		return SUCCESS;
	}
	
	
	@Action(value = "/valueDelete", results = @Result(name = "success", type = "json"))
	public void deleteDestination(){
		String reslut = "success";
		try {
			int id = Integer.parseInt(httpServletRequest
					.getParameter("id"));
			
			
			
			try {
				SysLog sl = new SysLog();
				sl.setContent("删除车属性,名字["+valueService.findById(id).getTypename()+"]");
				sl.setCreateDate(new Date());
				sysLogService.save(sl);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			valueService.removeById(id);
			
		} catch (Exception e1) {
			e1.printStackTrace();
			reslut = "failure";
		}

		httpServletResponse.setContentType("application/Json");
		JSONObject jsonResponse = new JSONObject();	
		try {
			jsonResponse.put("isSorF", reslut);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		try {
			httpServletResponse.getWriter().print(jsonResponse.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
/*	@Action(value = "/demoLoginAction", results = { @Result(name = SUCCESS, location = "/demoAction.action?type=manager", type = "redirect" ),
													@Result(name = "login", location = "/login.jsp" )})
	public String login() {
		String username = httpServletRequest.getParameter("username");
		String password = httpServletRequest.getParameter("password");
		if("admin".equals(username) && "admin".equals(password)){
			return SUCCESS;
		}else{
			return "login";
		}
	}*/
	
	
	@SuppressWarnings({ "unchecked", "unused" })
	@Action(value="/valueListAction")
	public void listDestination() {

		DataTableParam params = null;
		try {
			params = getParam();
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		HashMap<String, String> paramMap = convertToMap(params.getVoList());	
		String sEcho = paramMap.get("sEcho");
		Long iTotalRecords; // total number of records (unfiltered)
		Long iTotalDisplayRecords; //value will be set when code filters companies by keyword
		JSONArray data = new JSONArray(); //data that will be shown in the table

		int pageNumber = (Integer.parseInt(paramMap.get("iDisplayStart")) / Integer.parseInt(paramMap.get("iDisplayLength"))) + 1;

		StringBuffer hql =new StringBuffer( "from Value demo ");
		if (params.getIsQuery().equalsIgnoreCase("true")) {
			hql.append(" where 1 = 1 ");
			String typename = paramMap.get("typename").trim();		//属性名称
			String cheId = paramMap.get("cheId").trim();
			if (!"".equalsIgnoreCase(typename)) {
				hql.append(" and demo.typename like '%"+typename+"%' ");
			}
			
			if (!"".equalsIgnoreCase(cheId)) {
				hql.append(" and demo.cheId = "+cheId+"  ");
			}
		}
		
		String sCol = paramMap.get("iSortCol_0");
		String sortingColName =  paramMap.get("mDataProp_"+sCol);
		//asc or desc
	    String sdir = paramMap.get("sSortDir_0");
	   
	    if("0".equals(sortingColName)){
//	    	sortingColName = "dest.destination";
	    }else if("2".equals(sortingColName)){
	    	sortingColName = "demo.value";
	    }else if("1".equals(sortingColName)){
	    	sortingColName = "demo.typename";
	    }else if("5".equals(sortingColName)){
	    	sortingColName = "demo.createdate";
	    }
	    
    	if ("desc".equalsIgnoreCase(sdir)) {
	    	hql.append(" order by "+sortingColName +" desc");
	    }else{
	    	hql.append(" order by "+sortingColName );
	    }
	    

		Object[] values = null;
		Pagination pageMqDestination = valueService.pageQueryByHql(hql.toString(), values, hql.toString(), pageNumber, Integer.parseInt(paramMap.get("iDisplayLength")));
		iTotalRecords = pageMqDestination.getTotalCount();
		List<Value> companies = (List<Value>) pageMqDestination.getResult();
//		List<Value> companies = new LinkedList<Demo>();
//		for(Demo c : apps){
//			companies.add(c);
//		}
		
		iTotalDisplayRecords = pageMqDestination.getTotalCount();
		
	
		try {
			JSONObject jsonResponse = new JSONObject();			
			jsonResponse.put("sEcho", sEcho);
			jsonResponse.put("iTotalRecords", iTotalRecords);
			jsonResponse.put("iTotalDisplayRecords", iTotalDisplayRecords);
			
			
			
			

			int i = 1;
			for(Value c : companies){
				JSONArray row = new JSONArray();
				Che che = cheService.findById(c.getCheId());
				String name = "";
				if(null != che){
					name = che.getName();
				}
				
				/*int count = 0;
				
				//计算累加值
				DetachedCriteria detachedCriteriaValue = DetachedCriteria.forClass(ValueDetail.class);
				detachedCriteriaValue.add(Restrictions.eq("cheId", c.getCheId()));
				detachedCriteriaValue.add(Restrictions.eq("backupsState", Constant.VALUEDETAILNOTBACKUPS));
				
				//查询 累计输入值是否大于阀门值。
				List<ValueDetail> listValueDetails = valueDetailService.queryList(detachedCriteriaValue);

					//计算 累计输入值
					for(ValueDetail vd : listValueDetails){
						count = count + vd.getValuedetail();
					}*/
				
				
				
				row.put(i++);
				row.put(c.getTypename());
				row.put(c.getValue());
//				row.put(count);		//累加值
				row.put(c.getGrandTotalValue());
				row.put(name);
				row.put(dateformat.format(c.getCreatedate()));
				row.put(c.getId());
				data.put(row);
			}
			jsonResponse.put("resultList", data);
			httpServletResponse.setContentType("application/Json;charset=utf-8");
			httpServletResponse.getWriter().print(jsonResponse.toString());
			
		} catch (Exception e) {
			e.printStackTrace();
			httpServletResponse.setContentType("text/html");
			try {
				httpServletResponse.getWriter().print(e.getMessage());
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	
	
	
	@SuppressWarnings("rawtypes")
	@Action(value = "/testZTree", results = @Result(name = "success", type = "json"))
	public void testZTree(){
		String reslut = "success";
		List<Object> jsonDataList = new ArrayList<Object>();
		try {

			JsonData jd1 = new JsonData();
			jd1.setId(1);
			jd1.setpId(0);
			jd1.setOpen(false);
			jd1.setName("第一个节点");
			jsonDataList.add(jd1);
			for(int i = 0;i<5;i++){
				JsonData jd2 = new JsonData();
				jd2.setId(2+i);
				jd2.setpId(1);
				jd2.setOpen(true);
				jd2.setName("第"+i+"个节点");
				jsonDataList.add(jd2);
			}


			JsonData jd3 = new JsonData();
			jd3.setId(111);
			jd3.setpId(3);
			jd3.setChecked(true);
			jd3.setOpen(true);
			jd3.setName("第四个节点");
			jsonDataList.add(jd3);

			// demoService.removeById(Integer.parseInt(httpServletRequest
			// .getParameter("id")));

		} catch (Exception e1) {
			e1.printStackTrace();
			reslut = "failure";
		}
		Map m = new HashMap();
		m.put("result", reslut);
		m.put("jsonData", jsonDataList);
		httpServletResponse.setContentType("application/Json");
		JSONObject jsonResponse = new JSONObject();	
		try {
//			jsonResponse.put("result", reslut);
			jsonResponse.put("resultData", m);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		try {
			httpServletResponse.getWriter().print(jsonResponse.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public class JsonData {

		private int id;
		private int pId;
		private String name;
		private boolean open;
		private boolean checked;

		public int getId() {
			return id;
		}

		public void setId(int id) {
			this.id = id;
		}

		public int getpId() {
			return pId;
		}

		public void setpId(int pId) {
			this.pId = pId;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public boolean getOpen() {
			return open;
		}

		public void setOpen(boolean open) {
			this.open = open;
		}

		public boolean isChecked() {
			return checked;
		}

		public void setChecked(boolean checked) {
			this.checked = checked;
		}
	
	}

	public Value getValue() {
		return value;
	}

	public void setValue(Value value) {
		this.value = value;
	}


}
